package com.changgou.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.service.WeixinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import com.mysql.cj.x.protobuf.MysqlxDatatypes;
import entity.Result;
import entity.StatusCode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.amqp.RabbitRetryTemplateCustomizer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付控制层
 * @author zhengjd
 * @date 2020/5/20 20:44
 */
@RestController
@RequestMapping("/weixin/pay")
public class WeixinPayController {

    @Autowired
    private WeixinPayService weixinPayService;

    /**
     * 生成微信支付二维码
     * @param out_trade_no  订单号
     * @param money   订单金额
     * @return
     */
    @RequestMapping("/create/native")
    public Result createNative(String out_trade_no, String money ){
        Map<String,String> resultMap = weixinPayService.createNative(out_trade_no,money);
        return new Result(true, StatusCode.OK,"生成二维码成功",resultMap);
    }

    /**
     * 查询订单支付状态
     * @param out_trade_no  订单号
     * @return
     */
    @RequestMapping("/status/query")
    public Result queryPayStatus(String out_trade_no){
        Map<String,String> resultMap = weixinPayService.queryPayStatus(out_trade_no);
        return new Result(true,StatusCode.OK,"查询订单支付状态成功",resultMap);
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.pay.exchange.order}")
    private String exchange;
    @Value("${mq.pay.queue.order}")
    private String queue;
    @Value("${mq.pay.routing.key}")
    private String routing;

    /**
     * 支付信息回调（由微信支付系统调用本系统接口，需要响应给微信支付系统xml数据格式）
     * @param request
     * @return
     */
    @RequestMapping("/notify/url")
    public String notifyUrl(HttpServletRequest request){
        //微信支付系统以流的形式发送请求数据
        try {
            ServletInputStream inputStream = request.getInputStream();
            //获取输出流
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            //读取流数据
            while ((len=inputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }
            //将请求数据转化为字符串
            String requestPara = new String(outputStream.toByteArray(), "utf-8");
            //将字符串转化为map
            Map<String, String> map = WXPayUtil.xmlToMap(requestPara);
            //将消息发送到rabbitMQ队列中
            rabbitTemplate.convertAndSend(exchange,routing, JSON.toJSONString(map));
            System.out.println(requestPara);
            //响应数据
            HashMap<String, String> resultMap = new HashMap<>();
            resultMap.put("return_code","SUCCESS");
            resultMap.put("return_msg","OK");
            return WXPayUtil.mapToXml(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
